var mongoose = require('mongoose');
const Products = require('../model/products.model'); // 数据模型
// 增
exports.create = function(req, res, next) {
	const products = new Products(req.body);
	products.save().then(data => {
		res.json(data);
	});
};
// 删
exports.remove = function(req, res, next) {
	var id = req.params.id;
	Products.findByIdAndRemove(id, function(err, data) {
		res.json({
			message: '删除成功'
		});
	});
};

// // 改 req.body,req.query,req.params
exports.update = function(req, res, next) {
	const id = req.params.id;
	Products.findByIdAndUpdate(id, {
		$set: req.body
	}, {
		new: false
	}).then(data => {
		res.json(data);
	});
};

// // 查
exports.list = function(req, res, next) {
	var page = req.body.page ? req.body.page : 1;
	var rows = req.body.rows ? req.body.rows : 5;
	var queryCondition = {};

	if(req.body.name && req.body.name.trim().length > 0) {
		name = req.body.name;

		queryCondition = {
			name: new RegExp(name, 'i')
		};
	}

	if(req.body.cateId && req.body.cateId.trim().length > 0) {
		cateId = req.body.cateId;
		queryCondition = Object.assign(queryCondition, {
			cateId: cateId
		});
	}

	Products.paginate(queryCondition, {
		page: +page,
		limit: +rows
	}, function(
		err,
		result
	) {
		result.rows = result.docs;
		delete result.docs;
		res.json(result);
	});
};